package com.sc.datacollect.util;

import java.beans.PropertyVetoException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import com.mchange.v2.c3p0.ComboPooledDataSource;

/**
 * <p>
 * c3p0 配置oracle连接池
 * </p>
 */

public class DBConnPool {
	private static String driverClass = "";
	private static String jdbcUrl = "";
	private static String user = "";
	private static String password = "";
	private static Integer minPoolSize = 1;
	private static Integer maxPoolSize = 10;
	private static Integer acquireIncrement = 1;
	private static Integer initialPoolSize = 2;
	private static Integer maxIdleTime = 240;
	private static Integer acquireRetryAttempts = -1;

	private static final DBConnPool instance = new DBConnPool();
	private static ComboPooledDataSource cpds = new ComboPooledDataSource();

	static {
		driverClass = CommonConfig.orcldriverClass;
		jdbcUrl = CommonConfig.orcljdbcUrl;
		user = CommonConfig.orcluser;
		password = CommonConfig.orclpassword;
		cpds.setJdbcUrl(jdbcUrl);
		try {
			cpds.setDriverClass(driverClass);
		} catch (PropertyVetoException e) {
			e.printStackTrace();
		}
		cpds.setUser(user);
		cpds.setPassword(password);
		cpds.setMaxPoolSize(maxPoolSize);
		cpds.setMinPoolSize(minPoolSize);
		cpds.setAcquireIncrement(acquireIncrement);
		cpds.setInitialPoolSize(initialPoolSize);
		cpds.setMaxIdleTime(maxIdleTime);
		cpds.setAcquireRetryAttempts(acquireRetryAttempts);
	}

	private DBConnPool() {
	};

	public static DBConnPool getInstance() {
		return instance;
	}

	/**
	 * 获取链接
	 * 
	 * @return
	 */
	public static Connection getConnection() {
		try {
			return cpds.getConnection();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 释放链接
	 * 
	 * @param conn
	 */
	public static void free(Connection conn) {
		if (conn != null) {
			try {
				conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * 释放链接
	 * 
	 * @param conn
	 * @param psmt
	 */
	public static void free(Connection conn, PreparedStatement psmt) {
		try {
			if (psmt != null) {
				psmt.close();
			}

		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			free(conn);
		}
	}

	public static void free(Connection conn, PreparedStatement psmt, ResultSet rs) {
		try {
			if (rs != null) {
				rs.close();
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			free(conn, psmt);
		}
	}

	public static void free(Connection conn, Statement st, ResultSet rs) {
		try {
			if (rs != null)
				rs.close();
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			free(conn, st);
		}
	}

	public static void free(Connection conn, Statement st) {
		try {
			if (st != null) {
				st.close();
			}

		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			free(conn);
		}
	}
}
